import * as vscode from 'vscode';
import { ApiPanelProvider } from './ApiPilotWebviewView';
import { VerticalDiffManager } from '../../../src/diff/vertical/manager';
import { LLMFactory } from '../../../core/llm/llmFactory';
import { ApiCodeDecorator } from './ApiCodeDecorator';
import { ApiCodeLensProvider } from './ApiCodeLens';
import { FixCodeHandler } from './ApiFixCodeHandler';
import { ApiUsageAdapter, APIData } from './Service/ApiLocation';

export async function singleFileApiChange() {
    const currentFilePath = vscode.window.activeTextEditor?.document.uri.fsPath;
    if (!currentFilePath) {
        vscode.window.showErrorMessage('无法获取当前文件路径，请确保已打开文件。');
        return;
    }
    const filePathsArray = [currentFilePath];
    vscode.commands.executeCommand('HarmonyPilot.apiLocattion', filePathsArray, 11, 15);
}

export async function allFileApiChange() {
    const userResponse = await vscode.window.showWarningMessage(
        '扫描所有文件可能耗时较长，是否继续？',
        { modal: true },
        '确定',
    );

    if (userResponse !== '确定') {
        return;
    }
    const files = await vscode.workspace.findFiles('entry/**/*.ets', '**/node_modules/**', 1000);
    const filePathsArray = files.map(file => file.fsPath);
    if (filePathsArray.length === 0) {
        vscode.window.showErrorMessage('没有找到符合条件的文件。');
        return;
    }
    vscode.commands.executeCommand('HarmonyPilot.apiLocattion', filePathsArray, 12, 14);
}

export function actApiPilotCommand(
    context: vscode.ExtensionContext,
    verticalDiffManager: VerticalDiffManager,
    llmFactory: LLMFactory
) {
    const apiPanelProvider = new ApiPanelProvider(context, verticalDiffManager, llmFactory);
    const codeLensProvider = new ApiCodeLensProvider();
    const fixCodeHandler = new FixCodeHandler(verticalDiffManager, llmFactory);
    const apiUsageAdapter = new ApiUsageAdapter(context);
    context.subscriptions.push(
        vscode.window.registerWebviewViewProvider(
            'HarmonyPilot.apiPanel', // 视图标识符
            apiPanelProvider
        )
    );

    // 触发数据更新
    context.subscriptions.push(
        vscode.commands.registerCommand('HarmonyPilot.updateApiPanel', (data: APIData[]) => {
            apiPanelProvider.updateData(data);
        })
    );
    const decorator = new ApiCodeDecorator();
    context.subscriptions.push(
        vscode.commands.registerCommand('HarmonyPilot.decorateLine', (adapterCode: APIData) => {
            decorator.decorateLine(Number(adapterCode.line)-1, Number(adapterCode.startCol), Number(adapterCode.endCol));
            codeLensProvider.addCodeLens(adapterCode);
        })
    );

    context.subscriptions.push(
        vscode.languages.registerCodeLensProvider({ scheme: 'file' }, codeLensProvider)
    );
    context.subscriptions.push(
        vscode.commands.registerCommand('HarmonyPilot.fixCode', async (adapterCode: APIData) => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('未找到活动编辑器');
            return;
        }

        await vscode.window.withProgress(
            {
                location: vscode.ProgressLocation.Notification,
                title: '正在修复代码，请稍候...',
                cancellable: false,
            },
            async () => {
                codeLensProvider.handleFixCode(Number(adapterCode.line) - 1);
                const prompt = apiUsageAdapter.APIAdapter(adapterCode);
                await fixCodeHandler.fixCode(prompt);
                // 取消装饰器
                decorator.clearAllDecorations();
            }
        );
    })
    );
    // 触发数据更新
    context.subscriptions.push(
        vscode.commands.registerCommand('HarmonyPilot.apiLocattion', async (filePathsArray: [], startAPILevel: number, endAPILevel: number) => {
            await vscode.window.withProgress(
                {
                    location: vscode.ProgressLocation.Notification,
                    title: '正在检索需要变更的API，请稍候...',
                    cancellable: false,
                },
                async () => {
                    const newData = apiUsageAdapter.APILocation(filePathsArray, startAPILevel, endAPILevel);
                    apiPanelProvider.updateData(newData);
                }
            );
        })
    );
}
export function helloApiPilot() {
    const message = vscode.l10n.t('Hello World from HarmonyPilot!');
    vscode.window.showInformationMessage(message);
}
